//
//  SXNetworkTools.swift
//  swift网络框架的封装
//
//  Created by shengxinwei on 16/5/22.
//  Copyright © 2016年 shengxinwei. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

enum HTTPMethod {
    case GET
    case POST
}

class SXNetworkTools: AFHTTPSessionManager {
    //创建单例对象
    static let  sharedTools: SXNetworkTools = {
        let url = NSURL(string: API.hostName)
        let tools = SXNetworkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
    func request(ReqMethod: HTTPMethod , urlString: String , params: AnyObject? , progress:((prog:NSProgress) -> Void)? , finished: (responseObject: AnyObject?, error: NSError?)->Void) {
        
        
        //定义闭包参数 将相同的闭包当做参数传递
        let successReuslt = { (task: NSURLSessionDataTask, result: AnyObject?) -> () in
            //执行请求成功的回调
            finished(responseObject: result, error: nil)
        }
        
        let failureResult = { (task: NSURLSessionDataTask?, error: NSError) -> () in
            //执行失败的回调
            finished(responseObject: nil, error: error)
        }
        
        if ReqMethod == .GET {
            
            GET(urlString, parameters: params, progress: nil, success: successReuslt, failure: failureResult)
        }else
        {
            //  POST(urlString, parameters: params, success: successReuslt, failure: failureResult)
            
            POST(urlString, parameters: params, progress: nil, success: successReuslt, failure: failureResult)
        }
    }
    
}

extension SXNetworkTools {
    
    func loadAccessToken(codeNo: String , finished: (responseObject: AnyObject? , error: NSError?) -> ()) {
        let parameters = ["client_id" : client_id, "client_secret":client_secret, "grant_type": "authorization_code","code":codeNo,"redirect_uri":redirect_uri]
        
        request(.POST, urlString: API.loadAccessToken, params: parameters, progress: nil) { (responseObject, error) in
            finished(responseObject: responseObject, error: error)
        }
    }
    
    //加载用户信息
    func loadUserInfo(response: [String : AnyObject],finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        
        //用户访问接口权限的标识
        let token = response["access_token"]!
        let uid = response["uid"]!
        //字典中可以添加 nil嘛
        let parameters = ["access_token": token, "uid": uid]
        request(.GET, urlString: API.loadUserInfo, params: parameters, progress: nil, finished: finished)
    }
}

extension SXNetworkTools {
    
    func loadHomePageData(since_id: Int64,max_id: Int64 , finished: (responseObject: AnyObject?,error: NSError?)->()) {
        guard let token = SXUserAccountViewModel.sharedAccount.userAccount?.access_token else {
            return
        }
        var params = ["access_token": token]
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            //会有bug 会返回max_id 对应的微博
            params["max_id"] = "\(max_id - 1)"
        }
        
        SXNetworkTools.sharedTools.request(.GET, urlString: API.loadHomedata, params: params, progress: nil, finished: finished)
    }
    
    
    func sendStatus(status: String, images: [UIImage], finished: (responseObject: AnyObject?,error: NSError?)->()) {
        guard let token = SXUserAccountViewModel.sharedAccount.userAccount?.access_token else {
            return
        }
        
        let parameters = ["access_token": token,"status":status]
        
        if images.count > 0 {
            self.POST(API.sendImageStatus, parameters: parameters, constructingBodyWithBlock: { (formdata) in
                //将上传的二进制数据添加到formdata中
                /*
                 1.data          需要上传的二进制数据
                 2.name          服务器接收的字段
                 3.fileName      服务器存储的上传文件的名称  但是这个地方可以随便去  新浪微博服务器会自己根据自己的规则命名
                 4.mimeType      上传的文件的类型  application/octet-stream 忽略文件类型
                 */
                //将多图拼接到formdata中
                for image in images {
                    print(image)
                    let imageData = UIImagePNGRepresentation(image)!
                    formdata.appendPartWithFileData(imageData, name: "pic", fileName: "ococooc", mimeType: "application/octet-stream")
                }
                
                }, progress: nil, success: { (_, result) in
                    finished(responseObject: result, error: nil)
                }, failure: { (_, error) in
                    finished(responseObject: nil, error: error)
            })

            
        }else {
            request(.POST, urlString: API.sendStatus, params: parameters, progress: nil, finished: finished)
        }
        
    }
    
}




